package srx.open.com.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bmob.im.bean.BmobRecent;
import cn.bmob.im.db.BmobDB;
import de.greenrobot.event.EventBus;
import srx.open.com.R;
import srx.open.com.activity.ChatActivity;
import srx.open.com.adapter.MessageRecentAdapter;
import srx.open.com.bean.User;
import srx.open.com.dialog.DialogTips;
import srx.open.com.mode.ShowMsgNotifyMode;
import srx.open.com.utils.Log;
import srx.open.com.widgets.ScrollForeverTextView;

/**
 * 消息界面.
 */
public class MyMsgFragment extends BaseFragment {

    public static MyMsgFragment newInstance(String s) {
        MyMsgFragment myMsgFragment = new MyMsgFragment();
        return myMsgFragment;
    }

    private static final String TAG = "MyMsgFragment";

    @Bind(R.id.back_iv)
    ImageView backIv;
    @Bind(R.id.left_lay)
    LinearLayout leftLay;
    @Bind(R.id.left_tv)
    ScrollForeverTextView leftTv;
    @Bind(R.id.right_tv)
    TextView rightTv;
    @Bind(R.id.right_lay)
    LinearLayout rightLay;
    // 会话消息.
    @Bind(R.id.list)
    ListView listview;

    MessageRecentAdapter adapter; // 会话Adapter.

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my_msg, container, false);
        ButterKnife.bind(this, view);
        initAllViews(view);
        EventBus.getDefault().register(this);
        ButterKnife.bind(this, view);
        return view;
    }

    public void onEvent(ShowMsgNotifyMode showMsgNotifyMode) {
        if (showMsgNotifyMode.state.equals("MyMsgFragment.class")) {
            Log.d(TAG, "onEvent(ShowMsgNotifyMode showMsgNotifyMode) --> MyMsgFragment.class");
            if (!hidden) {
                refresh();
            }
        }
    }

    @Override
    public void initAllDatas() {

    }

    private void initAllViews(View viewRoot) {
        initTitles();
        //
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BmobRecent recent = adapter.getItem(position);
                // 重置未读消息
                BmobDB.create(getActivity()).resetUnread(recent.getTargetid());
                // 组装聊天对象
                User user = new User();
                user.setAvatar(recent.getAvatar());
                user.setNick(recent.getNick());
                user.setUsername(recent.getUserName());
                user.setObjectId(recent.getTargetid());
                // 会话消息.
                Log.d(TAG, "会话消息:" + user);
                Intent intent = new Intent(getActivity(), ChatActivity.class);
                intent.putExtra("User", user);
                startActivity(intent);
            }
        });
        listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                BmobRecent recent = adapter.getItem(position);
                showDeleteDialog(recent); // 删除.
                return true;
            }
        });
        //
        adapter = new MessageRecentAdapter(getActivity(),
                R.layout.listview_item_conversation, BmobDB.create(getActivity())
                .queryRecents());
        listview.setAdapter(adapter);
    }

    public void showDeleteDialog(final BmobRecent recent) {
        DialogTips dialog = new DialogTips(getActivity(), recent.getUserName(),
                "删除会话", "确定", true, true);
        // 设置成功事件
        dialog.SetOnSuccessListener(new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int userId) {
                deleteRecent(recent); // 删除回话.
            }
        });
        // 显示确认对话框
        dialog.show();
        dialog = null;
    }

    /**
     * 删除会话 deleteRecent
     */
    private void deleteRecent(BmobRecent recent) {
        adapter.remove(recent);
        BmobDB.create(getActivity()).deleteRecent(recent.getTargetid());
        BmobDB.create(getActivity()).deleteMessages(recent.getTargetid());
    }

    private void initTitles() {
        leftTv.setText(R.string.my_msg_title);
        rightLay.setVisibility(View.GONE);
        backIv.setVisibility(View.INVISIBLE);
    }

    private boolean hidden;

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        this.hidden = hidden;
        if (!hidden) {
            refresh();
        }
    }

    public void refresh() {
        try {
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    adapter = new MessageRecentAdapter(getActivity(),
                            R.layout.listview_item_conversation, BmobDB.create(
                            getActivity()).queryRecents());
                    listview.setAdapter(adapter);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!hidden) {
            refresh();
        }
    }

}
